package com.example.hello;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class RateActivity extends AppCompatActivity implements Runnable{
    public  static  final  String TAG="rate";
    private float dollarRate=0.1570f;
    private float euroRate=0.1430f;
    private float wonRate=192.1475f;
    Handler handler;
    TextView out;
    String today_date;
    String update_date;


    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate);

        out = findViewById(R.id.result);
        //加在上次保存的汇率值
        SharedPreferences sharedPreferences = getSharedPreferences("myrate", Activity.MODE_PRIVATE);

        dollarRate = sharedPreferences.getFloat("dollar_rate", 0.1570f);
        euroRate = sharedPreferences.getFloat("euro_rate", 0.1430f);
        wonRate = sharedPreferences.getFloat("won_rate", 192.1475f);
        update_date=sharedPreferences.getString("update_date","");

        Log.i(TAG,"onCreate:update_date="+update_date);
        //获取时间
        Date today = Calendar.getInstance().getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        today_date = formatter.format(today);
        Log.i(TAG,"onCreate:today="+today_date);

        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                //接收收件人为5的
                if(msg.what==5){
                    Bundle bdl = (Bundle) msg.obj;
                    dollarRate = bdl.getFloat("dollar_new");
                    euroRate = bdl.getFloat("euro_new");
                    wonRate = bdl.getFloat("won_new");
                }
                super.handleMessage(msg);
            }
        };

        //如果获得到的时间!=数据更新的时间,就更新
        if(!today_date.equals(update_date)){
            //更新，开启线程
            //开启线程(run)
            Log.i(TAG,"onCreate:更新汇率");
            Thread t = new Thread(this);
            t.start();
        }else{
            //不开启线程
            Log.i(TAG,"onCreate:不更新汇率");
        }




/*
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                //接收收件人为5的
                if(msg.what==5){
                    //接收消息
                    String str=(String)msg.obj;
                    Log.i(TAG,"handle:getmsg msg="+str);
                    out.setText(str);

                }
                super.handleMessage(msg);
            }
        };

 */

//        Thread t2=new Thread(new Runnable() {
//            @Override
//            public void run() {
//                //
//            }
//        });
//        //接受返回修改的汇率
//        Intent intent = getIntent();
//        dollarRate=intent.getFloatExtra("dollar_new",0.1570f);
//        euroRate=intent.getFloatExtra("euro_new",0.1430f);
//        wonRate=intent.getFloatExtra("won_new",192.1475f);
//
//        Log.i(TAG,"save:dollarRate"+dollarRate);
//        Log.i(TAG,"save:euroRate"+euroRate);
//        Log.i(TAG,"save:wonRate"+wonRate);
    }
    public void myclick(View btn){
        //获取用户输入数据
        EditText rmb = findViewById(R.id.rmb_inp);
        String str = rmb.getText().toString();

        //转换为double or float
        if (str.length()==0){
            //提示用户
            Toast.makeText(this, "请输入金额", Toast.LENGTH_SHORT).show();
            return;
        }
        Float s=Float.parseFloat(str);
        Float r=0.0f;
        //计算结果
        Log.i(TAG,"myclick:");
        if (btn.getId()==R.id.btn_dollar){
            r=dollarRate;
            s=s*r;
        }else if(btn.getId()==R.id.btn_euro){
            r=euroRate;
            s=s*r;
        }else{
            r=wonRate;
            s=s*r;
        }
        out.setText("结果为："+s);
        //((TextView)findViewById(R.id.result)).setText("结果为："+s);
    }
    public void open(View btn){
        //打开一个新窗口,传入汇率
        openconfig();
    }
    private void openconfig() {
        Intent intent=new Intent(this,CondigActivity.class);
        intent.putExtra("dollar_key",dollarRate);
        intent.putExtra("euro_key",euroRate);
        intent.putExtra("won_key",wonRate);

        Log.i(TAG,"openOne:dollarRate="+dollarRate);
        Log.i(TAG,"openOne:euroRate="+euroRate);
        Log.i(TAG,"openOne:wonRate="+wonRate);
        //startActivity(intent);
        //新窗口会返回该页面
        startActivityForResult(intent,3);
    }

    //接收数据返回的方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode==3 && resultCode==6){
            //request汇率修改页面返回的数据,result返回的全部修改的数据,说明data中包含bundle
            Bundle bdl=data.getExtras();
            //拆分放入数据
            dollarRate=bdl.getFloat("dollar_new");
            euroRate=bdl.getFloat("euro_new");
            wonRate=bdl.getFloat("won_new");

            //保存新的数据到sp中
            SharedPreferences sp=getSharedPreferences("myrate",Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor=sp.edit();
            editor.putFloat("dollar_rate",dollarRate);
            editor.putFloat("euro_rate",euroRate);
            editor.putFloat("won_rate",wonRate);
            editor.apply();

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.my_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.menu_setting){
            //执行方法
            openconfig();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void run() {
        Log.i(TAG,"run:---");
        //do....延时3s
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

//        //获得网络数据
//        URL url=null;
//        try {
//            url=new URL("https://www.usd-cny.com/bankofchina.htm");
//            HttpURLConnection http=(HttpURLConnection)url.openConnection();
//            InputStream in=http.getInputStream();
//
//            String html=inputStream2String(in);
//            Log.i(TAG,"run:html="+html);
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        try {
            Document doc= Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();
            String title=doc.title();
            Log.i(TAG,"run:title="+title);

//            Element table=doc.getElementsByTag("table").first();
            Element table=doc.selectFirst("table");
            //第8行第6列的元素 欧元
            Element td=table.selectFirst("tr:nth-child(8)>td:nth-child(6)");
            String euro=td.text();
            Log.i(TAG,"run:欧元="+100f/Float.parseFloat(euro));

            //第14行第6列的元素 韩元
            Element td2=table.selectFirst("tr:nth-child(14)>td:nth-child(6)");
            String won=td2.text();
            Log.i(TAG,"run:韩元="+100f/Float.parseFloat(won));

            //第27行第6列的元素 美元
            Element td3=table.selectFirst("tr:nth-child(27)>td:nth-child(6)");
            String dollar=td3.text();
            Log.i(TAG,"run:美元="+100f/Float.parseFloat(dollar));

            Bundle bundle=new Bundle();
            bundle.putFloat("dollar_new",100f/Float.parseFloat(dollar));
            bundle.putFloat("euro_new",100f/Float.parseFloat(euro));
            bundle.putFloat("won_new",100f/Float.parseFloat(won));
            //返回消息给主线程
            //获取MSG对象,收件人：5
            Message msg=handler.obtainMessage(5);
            //内容
            msg.obj=bundle;
            handler.sendMessage(msg);
            Log.i(TAG,"sendmsg ok");
            //保存新的数据到sp中
            SharedPreferences sp=getSharedPreferences("myrate",Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor=sp.edit();
            editor.putFloat("dollar_rate",dollarRate);
            editor.putFloat("euro_rate",euroRate);
            editor.putFloat("won_rate",wonRate);
            //保存本次数据更新的时间
            editor.putString("update_time",today_date);
            editor.apply();


//            //获取td元素
//            Elements tds=doc.getElementsByTag("td");
////            for(Element td:tds){
////                Log.i(TAG,"run:td="+td.text());
////
////            }
//            for(int i=0;i<tds.size();i+=6){
//                Element td1=tds.get(i);
//                Element td2=tds.get(i+5);
//                String str=td1.text();
//                String val=td2.text();
//                Log.i(TAG,"run:"+str+"→"+val);
//
//                if(str.equals("美元")){
//                    Log.i(TAG,"run:美元------------");
//                    dollarRate=100f/Float.parseFloat(val);
//                    Log.i(TAG,"run:dollarRate="+dollarRate);
//                }
//                if(str.equals("欧元")){
//                    euroRate=100f/Float.parseFloat(val);
//                    Log.i(TAG,"run:euroRate="+euroRate);
//                }
//                if(str.equals("韩元")){
//                    wonRate=100f/Float.parseFloat(val);
//                    Log.i(TAG,"run:wonRate="+wonRate);
//                }
//
//            }
//            //保存新的数据到sp中
//            SharedPreferences sp=getSharedPreferences("myrate",Activity.MODE_PRIVATE);
//            SharedPreferences.Editor editor=sp.edit();
//            editor.putFloat("dollar_rate",dollarRate);
//            editor.putFloat("euro_rate",euroRate);
//            editor.putFloat("won_rate",wonRate);
//            editor.apply();
//
//            Element td2=doc.selectFirst("body > section > div > div > article > table > tbody > tr:nth-child(14) > td:nth-child(6)");
//            Log.d(TAG, "run: td2="+td2.text());

        } catch (IOException e) {
            e.printStackTrace();
        }
/*
        //返回消息给主线程
        //获取MSG对象,收件人：5
        Message msg=handler.obtainMessage(5);
        //内容
        msg.obj="hello from run()";
        handler.sendMessage(msg);
        Log.i(TAG,"sendmsg ok");

 */

    }

    private String inputStream2String(InputStream inputStream) throws IOException{
        final int bufferSize=1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out= new StringBuilder();
        Reader in =new InputStreamReader(inputStream,"gb2312");
        while (true) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
            return out.toString();
    }
}